package com.asset.dispoal.file.bank.domain.service.command;

import com.alibaba.excel.EasyExcel;
import com.asset.dispoal.file.bank.domain.db.mapper.FileBankMapper;
import com.asset.dispoal.file.bank.domain.dto.FileBankDetailExportTemplate;
import com.asset.dispoal.file.bank.dto.FileBankExportRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Optional;

@Component
public class FileBankExportCommand {
    @Autowired
    private FileBankMapper fileBankMapper;

    public void execute(HttpServletResponse response, FileBankExportRequest request) {
        List<FileBankDetailExportTemplate> detailExportTemplateList = fileBankMapper.queryDetail(request);
        try {
            String title = Optional.ofNullable(request.getBankName()).get() + "流水明细.xlsx";
            EasyExcel.write(response.getOutputStream())
                    .sheet("流水明细")
                    .head(FileBankDetailExportTemplate.class).doWrite(detailExportTemplateList);
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(title, "UTF-8"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
